<?php
namespace app\restful\controller;
use app\restful\code\ErrorCode;
use app\restful\controller\Member;
use app\restful\controller\Article;
use think\Exception;

class Restful
{
    /**
     * @var User
     */
    private $_member;

    /**
     * @var
     */
    private $_article;

    /**
     * 请求方法
     * @var
     */
    private  $_requestMethods;

    /**
     * 请求的资源名称
     * @var
     */
    private $_resourceName;

    /**
     * 请求的资源ID
     * @var
     */
    private $_id;

    /**
     * 允许请求的资源列表
     * @var array
     */
    private $_allowResources = ['member','article'];

    /**
     * 允许请求的HTTP方法
     * @var array
     */
    private $_allowRequestMethods = ['GET','POST','PUT','DELETE','OPTIONS'];

    /**
     * 常用的状态码
     * @var array
     */
    private $_statusCode = [
       // 3    => 'ceshi',
        200  => 'OK',
        204  => 'No Content',
        400  => 'Bad Request',
        401  => 'Unauthorized',
        403  => 'Forbidden',
        404  => 'Not Found',
        405  => 'Methods Not Allowed',
        500  => 'Server Interval Error'
    ];

    /**
     * 转换JSON输出
     * @param $array
     */
    private function _json($array,$code=0)
    {
        if ($code === 0 && $array === null)
        {
            $code = 204;
        }elseif($code === 0 && $array !== null){
            $code = 200;
        }
        header('HTTP/1.1 '.$code.$this->_statusCode[$code]);
        header('Content-Type:application/json;charset:utf-8');
        echo json_encode($array,JSON_UNESCAPED_UNICODE);
        exit();
    }

    /**
     * 构造函数实例化对象
     * Restful constructor.
     * @param \app\restful\controller\Member $_member
     * @param \app\restful\controller\Article $_article
     */
    public function __construct(Member $_member,Article $_article)
    {
        $this->_member = $_member;
        $this->_article = $_article;
    }



    public function run(){
        ob_clean();
        try{
            $this->_setupRequestMethod();
            $this->_setupResource();
            if($this->_resourceName == 'member'){
              return  $this->_json($this->_handleUser());
            }else{
              return   $this->_json($this->_handleArticle());
            }
        }catch(Exception $e){
            $this->_json(['error'=>$e->getMessage(),'code'=>$e->getCode()],$e->getCode());
        }
    }

    /**
     * 请求用户资源
     * @return $this|void
     * @throws Exception
     */
    public function _handleUser()
    {
        ob_clean();
        if($this->_requestMethods != 'POST'){
            throw new Exception("请求方法不允许",405);
        }
        $body = $this->_getBodyParams();
        dump($body['pwd']);
        if(empty($body['username'])){
            throw new Exception("用户名不能为空",400);
        }
        if(empty($body['pwd'])){
            throw new Exception("密码不能为空",400);
        }
        return $this->_member->register($body['username'],$body['pwd']);
    }

    /**
     * 获取请求体
     * @return mixed
     * @throws Exception
     */
    private function _getBodyParams(){
        ob_clean();
        $raw = file_get_contents('php://input');
        if(!$raw) {
            throw new Exception("请求参数错误", 400);
        }
        return json_decode($raw,true);
    }

    /**
     * 请求文章资源
     */
    private function _handleArticle()
    {
        switch($this->_requestMethods){
            case 'POST':
                return $this->_handleArticleCreate();
            case 'PUT':
                return $this->_handleArticleUpdate();
            case 'DELETE':
                return $this->_handleArticleDelete();
            case 'GET':
                if(empty($this->_id)){
                    return $this->_handleArticleList();
                }else{
                    return $this->_handleArticleView();
                }
            default:
                throw new Exception("请求方法不被允许",400);
        }
    }

    /**
     * 文章创建
     */
    private function _handleArticleCreate(){
        $body = $this->_getBodyParams();
        //文章标题不能为空
       // if(empty($body['title'])){
           // throw  new Exception("文章标题不能为空",400);
       // }
        //文章内容不能为空
        //if(empty($body['content'])){
          //  throw new Exception("文章内容不能为空",400);
       // }
        //登录
         $user_id = $this->_userLogin($_SERVER['HTTP_USERNAME'],$_SERVER['HTTP_PWD']);
       // dump($user_id)=6;
        //插入数据库
        try{
           $arr_article = $this->_article->create($body['title'],$body['content'],$user_id);
            return $arr_article;
        }catch (Exception $e){
            if(in_array($e->getCode(),[
                ErrorCode::ARTICLE_TITLE_CANNOT_EMPTY,
                ErrorCode::ARTICLE_CONTENT_CANNOT_EMPTY
            ])){
                throw new Exception($e->getMessage(),400);
            }else{
                throw new Exception($e->getMessage(),500);
            }
        }



    }

    private function _userLogin($AUTH_USER,$AUTH_PWD){
        try{
            $user_id = $this->_member->login($AUTH_USER,$AUTH_PWD);
            return $user_id;
        }catch(Exception $e){
            if(in_array($e->getCode(),[
                  ErrorCode::USERNAME_CANNOT_EMPTY,
                  ErrorCode::PWD_CANNOT_EMPTY,
                  ErrorCode::USERNAME_OR_PWD_ERROR
            ])){
                throw new Exception($e->getMessage(),400);
            }else{
                throw new Exception($e->getMessage(),500);
            }
        }

    }


    /**
     * 文章编辑
     */
    private function _handleArticleUpdate(){
        $body = $this->_getBodyParams();
        $user_id = $this->_userLogin($_SERVER['HTTP_USERNAME'],$_SERVER['HTTP_PWD']);
        try{
            $arr_article = $this->_article->edit($body['article_id'],$body['title'],$body['content'],$user_id);
            return $arr_article;
        }catch (Exception $e){
            if($e->getCode() == ErrorCode::NO_AUTH){
                throw new Exception($e->getMessage(),403);
            }elseif(
                $e->getCode() === ErrorCode::REQUEST_PARAMS_ERROR
            ) {
                throw new Exception($e->getMessage(),400);
            }elseif($e->getCode() === ErrorCode::ARTICLE_NULL) {
            }
            else{
                throw new Exception($e->getMessage(),500);
            }
        }
    }

    /**
     * 文章列表
     */
    private function _handleArticleList(){
         //无需登录
        try{
            $arr_article = $this->_article->getList();
            return $arr_article;
        }catch (Exception $e){
                throw new Exception($e->getMessage(),500);
        }
    }

    /**
     * 单个文章
     */
    private function _handleArticleView(){
        //无需登录
        try{
           return $this->_article->view($this->_id);
        }catch (Exception $e){
            if($e->getCode() == ErrorCode::ARTICLE_NULL){
                throw new Exception($e->getMessage(),204);
            }else{
                throw new Exception($e->getMessage(),500);
            }
        }
    }





    /**
     * 初始化请求方法
     */
    private function _setupRequestMethod()
    {
        $this->_requestMethods = $_SERVER['REQUEST_METHOD'];
        if(!in_array($this->_requestMethods,$this->_allowRequestMethods)){
            throw new Exception("请求方法不允许",405);
        }

    }

    /**
     * 初始化资源路径
     * @throws Exception
     */
    private function  _setupResource()
    {
        $path = $_SERVER['PATH_INFO'];
        $param = explode('/',$path);

        $this->_resourceName = $param[3];
        if(!in_array($this->_resourceName,$this->_allowResources)){
            throw new Exception("请求资源名称不存在",400);
        }
        if(!empty($param[4])){
            $this->_id = $param[4];
        }

    }




}